package one.stand.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import one.stand.code.RedisCode;
import one.stand.config.CardPosterConfig;
import one.stand.entity.GoodsPosterEntity;
import one.stand.entity.websocket.CommodityInfoEntity;
import one.stand.enums.SeeRecordEnums;
import one.stand.model.*;
import one.stand.request.*;
import one.stand.response.CompanyResponse;
import one.stand.response.GoodSpecResponse;
import one.stand.response.GoodsResponse;
import one.stand.response.GoodstypeResponse;
import one.stand.service.CompanyAccontService;
import one.stand.service.GoodsService;
import one.stand.service.WxSunCodeService;
import one.stand.util.OssUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

/**
 * @author Administrator
 */
@Service
public class GoodsServiceImpl extends PublicBaseService implements GoodsService {

    @Override
    public ResultModel getCompanyInfo(CompanyRequest request) {
        if(request == null && request.getCompanyId() == null){
            return ResultModel.checkParamFail();
        }
        CompanyModel model = new CompanyModel();
        BeanUtils.copyProperties(request, model);
        model.setMyUserId(request.getId().intValue());
        CompanyModel companyModel = companyMapper.selectCompanyGoodsType(model);
        CompanyResponse companyResponse = new CompanyResponse();
        if (companyModel == null) {
            return ResultModel.noData();
        }
        BeanUtils.copyProperties(companyModel, companyResponse);
        return ResultModel.success(companyResponse);
    }

    @Override
    public ResultModel getGoodsType(GoodstypeRequest request) {
        if(request == null){
            return ResultModel.checkParamFail();
        }
        GoodstypeModel model = new GoodstypeModel();
        BeanUtils.copyProperties(request, model);
        model.setUserId(request.getId().intValue());
        List<GoodstypeModel> list = goodstypeMapper.selectGoodsType(model);
        if (list == null || list.size() < 1) {
            return ResultModel.noData();
        }
        List<GoodstypeResponse> responseList = new ArrayList<>();
        list.forEach(obj -> {
            {
                GoodstypeResponse response = new GoodstypeResponse();
                BeanUtils.copyProperties(obj, response);
                responseList.add(response);
            }
        });
        return ResultModel.success(responseList);
    }

    @Override
    public ResultModel getGoodsList(GoodsRequest request) {
        if(request == null){
            return ResultModel.checkParamFail();
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        GoodsModel model = new GoodsModel();
        BeanUtils.copyProperties(request, model);
        if(request.getGoodstypeId() == null || request.getGoodstypeId() <= 0){
            model.setGoodstypeId(null);
        }
        List<GoodsModel> list = goodsMapper.selectGoodsInfo(model);
        if (list == null || list.size() < 1) {
            return ResultModel.noData();
        }
        boolean fal = request.getMyCardId() == null || !request.getMyCardId().equals(request.getCardId());
        if (fal) {
            //添加查看记录
            addSeeRecord(request.getId().intValue(), request.getCardId(), null, SeeRecordEnums.PRODUCT.getCode(), null);
        }
        List<GoodsResponse> responseList = new ArrayList<>();
        list.forEach(obj -> {{
            GoodsResponse response = new GoodsResponse();
            BeanUtils.copyProperties(obj, response);
            responseList.add(response);
        }});
        PageInfo<GoodsResponse> pageList = new PageInfo<>(responseList);
        return ResultModel.success(pageList.getList());
    }

    @Override
    public ResultModel getGoodSpec(GoodSpecRequest request) {
        GoodSpecModel model = new GoodSpecModel();
        if (request != null) {
            BeanUtils.copyProperties(request, model);
        }
        List<GoodSpecModel> list = goodSpecMapper.getSpec(model);
        if (list == null || list.size() < 1) {
            return ResultModel.noData();
        }
        List<GoodSpecResponse> responseList = new ArrayList<>();
        list.forEach(obj -> {{
            GoodSpecResponse response = new GoodSpecResponse();
            BeanUtils.copyProperties(obj, response);
            responseList.add(response);
        }});
        return ResultModel.success(responseList);
    }

    @Override
    public ResultModel getGoodsInfo(GoodsRequest request) {
        if(request == null || request.getGoodsId() == null){
            return ResultModel.checkParamFail();
        }
        GoodsModel model = new GoodsModel();
        BeanUtils.copyProperties(request, model);
        model.setIsDel(0);
        List<GoodsModel> list = goodsMapper.getGoodsInfo(model);
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        boolean fal = request.getGoodsId() != null && (request.getMyCardId() == null || !request.getMyCardId().equals(request.getCardId()));
        if (fal) {
            //添加查看记录
            addSeeRecord(request.getId().intValue(), request.getCardId(), list.get(0).getCompanyId(), SeeRecordEnums.PRODUCT.getCode(), request.getGoodsId());
        }
        GoodsResponse response = new GoodsResponse();
        BeanUtils.copyProperties(list.get(0), response);
        if(list.get(0).getIsAssemble() == 1) {
            response.setAssembleModelList(assembleMapper.assembleModelList(request.getGoodsId()));
            response.setGoodsAssembleModel(goodsAssembleMapper.getGoodsAssemble(request.getGoodsId()));
        }
        return ResultModel.success(response);
    }

    @Autowired
    private CardPosterConfig cardPosterConfig;
    @Autowired
    private WxSunCodeService wxSunCodeService;
    @Autowired
    private CompanyAccontService companyAccontService;
    @Autowired
    private OssUtil ossUtil;
    @Override
    public ResultModel goodsCard(GoodSpecRequest request) {
        if(request.getSpecId()==null){
            return ResultModel.checkParamFail();
        }
        CommodityInfoEntity commodityInfoEntity=goodSpecMapper.getSendMessage(request.getSpecId().longValue());
        if(null==commodityInfoEntity){
            return  ResultModel.fail("商品不存在");
        }
        String  sunCodeUrl = null;
        if(StringUtils.isBlank(sunCodeUrl)){
            CompanyAccountModel companyAccountModel= companyAccontService.selectByCompanyKeyDefault(new CompanyAccountRequest(){{
                setCompanyId(commodityInfoEntity.getCompanyId());
            }}) ;


            StringBuffer stringBuffer = new StringBuffer();
            //名片id
            stringBuffer.append("card=").append(businessCardMapper.getBoosCardId(commodityInfoEntity.getCompanyId()));
            //公司id
            stringBuffer.append("&c=").append(commodityInfoEntity.getCompanyId());
            //分类id
            stringBuffer.append("&s=").append(commodityInfoEntity.getSpecId());
            //商品id
            stringBuffer.append("&g=").append(commodityInfoEntity.getGoodsId());

            JSONObject paramJson = new JSONObject();
            paramJson.put("scene", stringBuffer);
            paramJson.put("page", goodsSunCode);
            log.info("商品太阳码参数：{}", paramJson.toJSONString());
            sunCodeUrl =wxSunCodeService.getWxCode(paramJson, companyAccountModel.getAppId(), companyAccountModel.getAppSecret());
            redisUtil.set(RedisCode.getGoodsSunCode(commodityInfoEntity.getGoodsId()), sunCodeUrl);
        }
        log.info("生成太阳码：{}",sunCodeUrl);
        if(StringUtils.isBlank(sunCodeUrl)){
            return ResultModel.fail("生成太阳码失败");
        }

//        String goodsCardUrl=redisUtil.get(RedisCode.getGoodsCard(commodityInfoEntity.getSpecId(),request.getId()));
        String goodsCardUrl;
        if(true){
            String url=commodityInfoEntity.getCoverImg();
            if(StringUtils.isBlank(url)){
                url=commodityInfoEntity.getUrl();
            }
            UserModel userModel=userMapper.selectByPrimaryKey(request.getId().intValue());
            GoodsPosterEntity goodsPosterEntity=new GoodsPosterEntity();
            goodsPosterEntity.setImagePath(cardPosterConfig.getGoodsCard());
            goodsPosterEntity.setGoodsUrl(url);
            goodsPosterEntity.setMoney(commodityInfoEntity.getPrice()/100.0+"");
            goodsPosterEntity.setGoodsName(commodityInfoEntity.getGoodsName());
            goodsPosterEntity.setUserName(new String(Base64.getDecoder().decode(userModel.getNickeName())));
            goodsPosterEntity.setUserLogo(userModel.getAvatarUrl());
            goodsPosterEntity.setSunCodeUrl(sunCodeUrl);
            goodsCardUrl =ossUtil.uploadObjectOSS(imageGenerateUtil.goodsCard(goodsPosterEntity),"png");
            //redisUtil.set(RedisCode.getGoodsCard(commodityInfoEntity.getSpecId(),request.getId()),goodsCardUrl);
        }
        return ResultModel.success(goodsCardUrl);
    }
}
